﻿using System.Collections.Generic;
using SG;
using UnityEngine;
#pragma warning disable 0168 // variable declared but not used.
#pragma warning disable 0219
#pragma warning disable 0414
namespace SG {
    public class Updater:MonoBehaviour{

	private Dictionary<System.Action,UpdateHandler> handlers=new Dictionary<System.Action,UpdateHandler>();
	
	public float deltaTime{
		get;
		private set;
	}
	
	public float time{
		get;
		private set;
	}
	
	public float timeScale{
		get;
		set;
	}
	
	public static Updater Get(GameObject go){
		Updater updater=go.GetComponent<Updater>();
		if(updater==null){
			updater=go.AddComponent<Updater>();
			updater.deltaTime=0;
			updater.time=0;
			updater.timeScale=1;
		}
		return updater;
	}
	
	public static void Add(GameObject go,System.Action update){
		Updater updater=Updater.Get(go);
		updater.handlers.Add(update,new UpdateHandler(update));
	}
	
	public static void Remove(GameObject go,System.Action update){
		Updater updater=Updater.Get(go);
		if(updater.handlers.ContainsKey(update)){
			updater.handlers[update].disabled=true;
			updater.handlers.Remove(update);
		}
	}
	
	void Update(){
		deltaTime=Time.deltaTime*timeScale;
		if(deltaTime>0){
			time+=deltaTime;
			foreach(UpdateHandler handler in new List<UpdateHandler>(handlers.Values)){
				if(!handler.disabled){
					handler.update();
				}
			}
		}
	}
	
	class UpdateHandler{
		public bool disabled;
		public System.Action update;
		public UpdateHandler(System.Action update){
			this.update=update;
		}
	}
}
}